import store from './index'
import toast from '@/utils/toast'
import generateID from '@/utils/generateID'
import { deepCopy } from '@/utils/utils'
import ClipboardJS from "clipboard";

export default {
    state: {
        copyData: null, // 复制粘贴剪切
        isCut: false,

        copyDataSys: null,
        isCutSys: false,
    },
    mutations: {
        copy(state) {
            if (!state.curComponent) {
                toast('请选择组件')
                return
            }

            // 如果有剪切的数据，需要先还原
            restorePreCutData(state)
            copyData(state)

            state.isCut = false
        },

        copysys(state) {
            if (!state.curComponent) {
                toast('请选择组件')
                return
            }

            state.copyDataSys = {
                data: deepCopy(state.curComponent),
                index: state.curComponentIndex,
            }

            // state.copyDataSys = {
            //     data: JSON.parse( JSON.stringify( state.curComponent ) ) ,
            //     index: state.curComponentIndex,
            // }

            //拷贝到系统剪切板
            copyToSysClip( JSON.stringify( state.copyDataSys ) )

            state.isCutSys = false
        },        

        paste(state, isMouse) {
            if (!state.copyData) {
                toast('请选择组件')
                return
            }

            const data = state.copyData.data

            if (isMouse) {
                data.style.top = state.menuTop
                data.style.left = state.menuLeft
            } else {
                data.style.top += 10
                data.style.left += 10
            }

            store.commit('addComponent', { component: deepCopyHelper(data) })
            if (state.isCut) {
                state.copyData = null
            }
        },

        pastesys(state, isMouse) {
            // handleReadClip( state )
            if (navigator.clipboard && navigator.clipboard.readText){
                navigator.clipboard.readText()
              .then(text => {
                // console.log('从剪贴板读取的内容:', text);
                state.copyDataSys = JSON.parse( text )
                if (!state.copyDataSys) {
                    console.log( state.copyDataSys )
                    toast('请选择组件')
                    return
                }
    
                const data = state.copyDataSys.data
    
                if (isMouse) {
                    data.style.top = state.menuTop
                    data.style.left = state.menuLeft
                } else {
                    data.style.top += 10
                    data.style.left += 10
                }
    
                store.commit('addComponent', { component: deepCopyHelper(data) })
    
                // if (state.isCut) {
                //     state.copyData = null
                // }                  
                
                // store.commit('addComponent', { component: data, index })
                
                // alert(`剪贴板内容: ${text}`);
              })
              .catch(err => {
                console.error('读取剪贴板失败:', err);
                alert('无法读取剪贴板内容，请检查权限或浏览器支持情况。');
              });
            }
        },

        cut(state) {
            if (!state.curComponent) {
                toast('请选择组件')
                return
            }

            // 如果重复剪切，需要恢复上一次剪切的数据
            restorePreCutData(state)
            copyData(state)

            store.commit('deleteComponent')
            state.isCut = true
        },
    },
}

// 恢复上一次剪切的数据
function restorePreCutData(state) {
    if (state.isCut && state.copyData) {
        const data = deepCopy(state.copyData.data)
        const index = state.copyData.index
        store.commit('addComponent', { component: data, index })
        if (state.curComponentIndex >= index) {
            // 如果当前组件索引大于等于插入索引，需要加一，因为当前组件往后移了一位
            state.curComponentIndex++
        }
    }
}

function copyData(state) {
    state.copyData = {
        data: deepCopy(state.curComponent),
        index: state.curComponentIndex,
    }
}

function deepCopyHelper(data) {
    const result = deepCopy(data)
    result.id = generateID()
    if (result.component === 'Group') {
        result.propValue.forEach((component, i) => {
            result.propValue[i] = deepCopyHelper(component)
        })
    }

    return result
}

function copyToSysClip(  textToCopy  ){
    // 创建一个隐藏元素
    const hiddenElement = document.createElement('button');
    hiddenElement.setAttribute('data-clipboard-text', textToCopy);
    hiddenElement.id = "copy-btn"
    document.body.appendChild(hiddenElement);

    // 初始化 Clipboard.js
    const clipboard = new ClipboardJS(hiddenElement);

    // 绑定点击事件
    //document.getElementById('copy-btn')
    hiddenElement.addEventListener('click', () => {
      hiddenElement.click(); // 触发 Clipboard.js 操作
      console.log( "click" )
      // alert('内容已成功复制到剪贴板！');
    });

    // 移除 Clipboard.js 和隐藏元素
    clipboard.on('success', () => {
      document.body.removeChild(hiddenElement);
      clipboard.destroy();
      console.log( "remove clipboard" )
    });

    hiddenElement.click( )  //模拟点击
}

function handleReadClip(  state ){
    if (navigator.clipboard && navigator.clipboard.readText){
        navigator.clipboard.readText()
      .then(text => {
        state.copyDataSys = JSON.parse( text )
        // store.commit('addComponent', { component: data, index })
        // console.log('从剪贴板读取的内容:', text);
        // alert(`剪贴板内容: ${text}`);
      })
      .catch(err => {
        console.error('读取剪贴板失败:', err);
        alert('无法读取剪贴板内容，请检查权限或浏览器支持情况。');
      });
    }

}